<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="分类名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button  type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:type:add']"
        >新增</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['system:type:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['system:type:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:type:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="typeList"   row-key="typeId"   default-expand-all  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <!--      @selection-change="handleSelectionChange"-->
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="类别ID" align="center" prop="typeId" />
      <el-table-column label="分类名称" align="center" prop="typeName" />
      <el-table-column label="服务类型" align="center" prop="sysModel" :formatter="sysFormat"  />
      <el-table-column label="类别图标" align="center" prop="typeUrl"   :formatter="urlFormat"     >
        <template slot-scope="scope">
          <img :src="scope.row.typeUrl" alt="" width="50px" height="50px" >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:type:remove']"
          >删除</el-button>

          <el-button v-if="scope.row.fenleiInfo"
                     size="mini"
                     type="text"
                     icon="el-icon-magic-stick"
                     @click="handlefenleiInfo(scope.row)"

          >分类详情</el-button>
          <!--             v-hasPermi="['system:type:edit']"-->
          <el-button  v-if="scope.row.shuxingList"
                      size="mini"
                      type="text"
                      icon="el-icon-coin"
                      @click="handleshuxingList(scope.row)"

          >属性列表</el-button>
          <!--          v-hasPermi="['system:type:edit']"-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" >
            <el-form-item label="分类名称" prop="typeName">
              <el-input v-model="form.typeName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentTypeId">
              <treeselect   v-model="form.parentTypeId" :options="typeOptions" placeholder="选择上级分类"  :normalizer="normalizer" @select="treeselectfun"   />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="status">
              <el-switch
                v-model="form.status"
                active-text="启用"
                active-value="0"
                inactive-text="停用"
                inactive-value="1"
                >
<!--                @change="momentSwitchChange"-->
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务类型" prop="sysModel" v-show="!form.parentTypeId">
              <el-select v-model="form.sysModel" placeholder="服务类型" clearable size="small">
                <el-option
                  v-for="dict in sysOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--        <el-form-item label="父级类型" prop="parentTypeId" >-->
          <!--          <treeselect v-model="form.parentTypeId" :options="typeOptions" placeholder="选择上级部门"   :normalizer="normalizer" />-->
          <!--        </el-form-item>-->

          <!--上传图片-->
          <el-col :span="24">
            <el-form-item label="上传图片">
              <el-upload
                class="upload-demo"
                :action="url"
                :headers="headers"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleImageSuccess"
                multiple
                list-type="picture"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传图片格式文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {list, listType, getType, delType, addType, updateType, exportType , treeselect  } from "@/api/system/type";
  import {getData} from "@/api/system//dict/data";
  import { getToken } from '@/utils/auth'
  import { upload } from "@/api/system/type";
  import store from '@/store'
  import Treeselect from "@riophae/vue-treeselect";
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  let that;
  export default {
    components: { Treeselect },
    name: "Type",

    beforeCreate: function () {
      that = this;
    },
    data() {
      return {
        str:'',
        defaultProps: {
          children: 'children',
          label: 'typeName'
        },
        // 部门部门树选项
        typeOptions: undefined,
        // 服务类型字典
        sysOptions: [],
        //上传文件列表
        fileList:[],
        // // //上传headers
        headers:{
          'Authorization': null
        },
        // //url  上传接口地址
        url:null,
        options: {
          img: store.getters.avatar, //裁剪图片的地址
          autoCrop: true, // 是否默认生成截图框
          autoCropWidth: 200, // 默认生成截图框宽度
          autoCropHeight: 200, // 默认生成截图框高度
          fixedBox: true // 固定截图框大小 不允许改变
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 分类表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          ancestors: undefined,
          typeName: undefined,
          sysModel: undefined,
          parentTypeId: undefined,
          level: undefined,
          typeUrl: undefined,
          userId: undefined,
          status: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },
        apiUrl:'',//接口前缀
      };
    },
    created() {
      this.getList();  //进入页面获取列表
      this.getUrl()  //获取拼接url
      //获取字典
      this.getDicts("sys_model").then(response => {
        console.log(response)
        this.sysOptions = response.data;
      });

      // this.getDicts("sys_const_unit").then(response => {
      //   console.log('费用单位字典',response)
      // });
      //
      // this.getDicts("sys_mode").then(response => {
      //   console.log('计费方式字典',response)
      // });
      //
      //
      // this.getDicts("sys_attribute").then(response => {
      //   console.log('瞬间属性',response)
      // });

      this.getData()
    },
    filters: {
      capitalize: function (value) {
        let url =   process.env.VUE_APP_BASE_API+'/common/upload'
        // var url = that.url.substring(0,that.url.length-1)
        console.log( url + value)
        return  url + value
      }
    },
    methods: {



      treeselectfun(e,instanceId){
        console.log(e,instanceId)
        this.form.sysModel = e.sysModel
        // if(!!e.parentTypeId){
        //   this.form.ancestors = e.parentTypeId
        // }

        // this.str = ''
        // var arr = new  Array()
        // arr[0]=e
        // this.parentTypeIdList(arr)
        // console.log("str", this.str)
      },
      parentTypeIdList(datas) {
        //遍历树  获取id数组
        // var str = ''
        for (var i in datas) {
          if (!!datas[i].parentTypeId) {
            this.str=this.str+','+datas[i].parentTypeId
            // console.log(datas[i].parentTypeId)
          }
          if (datas[i].children) {
            this.parentTypeIdList(datas[i].children);
          }

        }},
// // 字典状态字典翻译  url  拼接

      urlFormat(row, column) {
        console.log(111)
        // console.log(process.env.VUE_APP_BASE_API + row.typeUrl)
        // return   process.env.VUE_APP_BASE_API  +  row.typeUrl;
        return '11'
      },



//后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
      normalizer(node){
        //去掉children=[]的children属性
        if(node.children && !node.children.length){
          delete node.children;
        }
        return {
          id: node.typeId,
          label:node.typeName,
          children:node.children
        }
      },
      setName(datas){
        //遍历树  获取id数组
        // var str=''
        for(var i in datas){
          // this.expandedKeys.push(datas[i].id)
          if(datas[i].typeUrl){
            datas[i].typeUrl =    process.env.VUE_APP_BASE_API + datas[i].typeUrl
          }
          if(!!datas[i].parentTypeId){
            //属性列表
            datas[i].shuxingList='shuxingList'
            //分类详情
            datas[i].fenleiInfo='fenleiInfo'

          }
          if(datas[i].children){
            this.setName(datas[i].children);
          }
          // console.log("str",str)
          this.typeList = datas
          this.typeOptions = datas

        }
      },
      // 查询type列表
      getList() {
        this.loading = true;
        list().then(response => {
          console.log('查询type列表',response)
          this.setName(response.data)
          // this.childrenUrl(response.data)
          // if (response.data.children>0)

          // response.data.forEach((items,i)=>{
          //   if(!!items.typeUrl){
          //     items.typeUrl =    process.env.VUE_APP_BASE_API + items.typeUrl
          //     console.log( items.typeUrl)
          //     this.fileList.length=0
          //
          //
          //
          //
          //     if (items.children.length>0){
          //       items.children.forEach((items1,i)=>{
          //         if(!!items1.typeUrl){
          //           items1.typeUrl =    process.env.VUE_APP_BASE_API + items1.typeUrl
          //           console.log( items1.typeUrl)
          //
          //
          //           if (items1.children.length>0){
          //             items1.children.forEach((items2,i)=>{
          //               if(!!items2.typeUrl){
          //                 items2.typeUrl =    process.env.VUE_APP_BASE_API + items2.typeUrl
          //                 console.log( items2.typeUrl)
          //
          //
          //                 if (items2.children.length>0){
          //                   items2.children.forEach((items3,i)=>{
          //                     if(!!items3.typeUrl){
          //                       items3.typeUrl =    process.env.VUE_APP_BASE_API + items3.typeUrl
          //                       console.log( item32.typeUrl)
          //                     }else {
          //                       items2.typeUrl = ""
          //                     }
          //                   })
          //                 }
          //
          //
          //               }else {
          //                 items1.typeUrl = ""
          //               }
          //             })
          //           }
          //
          //
          //         }else {
          //           items1.typeUrl = ""
          //         }
          //       })
          //     }
          //   }else {
          //     items.typeUrl = ""
          //   }
          // })










          //     this.typeList = response.rows;
          //     this.total = response.total;
          //     this.loading = false;


          // this.typeList = response.data;
          // this.typeOptions = response.data;

          this.loading = false;
        });
      },
      // 字典状态字典翻译
      sysFormat(row, column) {
        // console.log(this.sysOptions)
        // console.log(row.sysModel)
        return this.selectDictLabel(this.sysOptions, row.sysModel);
      },
      getData(){
        //  查询数据字典详情
        getData(15).then(res=>{
          console.log(res)
        })
      },

      //上传图片************************************************************
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleImageSuccess(res, file, fileList) {
        console.log(res)
        console.log(file)
        console.log(file.raw)
        console.log('fileList',fileList[0].response.fileName)
        // console.log('图片地址'.fileList[0].response.fileName)
        this.form.typeUrl = fileList[0].response.fileName
        // let formData = new FormData();
        // formData.append("avatarfile", file.raw);
        // console.log(formData);
        // upload(formData).then(response => {
        //   console.log(response)
        //   this.form.typeUrl = response.imgUrl
        //   console.log(this.form.url)
        // }).catch(err=>{
        //   console.log(err)
        // });
      },
      handleRemove(file, fileList) {
        this.fileList.length=0
        this.form.typeUrl = ""
        console.log( this.form)
        console.log(this.fileList)
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      // 上传图片
      uploadImg(file) {
        this.$refs.cropper.getCropBlob(data => {
          console.log(data)
          let formData = new FormData();
          formData.append("avatarfile", data);
          console.log(formData);
          //******************************************************************************************
          upload(formData).then(response => {
            // uploadAvatar(formData).then(response => {
            console.log(response)
            //拿到图片地址
            this.form.typeUrl = response.imgUrl
            console.log(this.form.typeUrl)
            if (response.code === 200) {
              this.openhead = false;
              this.options.img = process.env.VUE_APP_BASE_API + response.imgUrl;
              this.msgSuccess("修改成功");
            } else {
              this.msgError(response.msg);
            }
            this.$refs.cropper.clearCrop();
          }).catch(err=>{
            console.log(err)
          });
        });
      },
      // // //获取图片上传地址
      // getUrl(){
      //   console.log("接口前缀", process.env.VUE_APP_BASE_API)
      //   //******************************************************************************
      //   let url =   process.env.VUE_APP_BASE_API+'/system/user/profile/avatar'
      //   console.log("整体接口",url)
      //   this.url = url
      //   this.headers.Authorization ='Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      // },
      getUrl(){
        console.log("接口前缀", process.env.VUE_APP_BASE_API)
        //******************************************************************************
        let url =   process.env.VUE_APP_BASE_API+'/common/upload/'
        this.url = url
        this.apiUrl = url
        console.log("整体接口",url)
        this.headers.Authorization ='Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      },


      /** 查询分类列表 */
      // getList() {
      //   this.loading = true;
      //   console.log(this.queryParams)
      //   listType(this.queryParams).then(response => {
      //     console.log(response)
      //     console.log(process.env.VUE_APP_BASE_API)
      //     response.rows.forEach((items,i)=>{
      //       if(!!items.typeUrl){
      //         items.typeUrl =    process.env.VUE_APP_BASE_API + items.typeUrl
      //         this.fileList.length=0
      //       }else {
      //         items.typeUrl = ""
      //       }
      //     })
      //     this.typeList = response.rows;
      //     this.total = response.total;
      //     this.loading = false;
      //   }).catch(err=>{
      //     console.log(err)
      //     this.loading = false;
      //   });
      // },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          ancestors: undefined,
          typeName: undefined,
          sysModel: undefined,
          typeId: undefined,
          parentTypeId: undefined,
          level: undefined,
          typeUrl: undefined,
          userId: undefined,
          status: "0",
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        };
        this.fileList=[]
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.typeId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加分类";
      },
      /** 修改按钮操作 */
      //分类详情
      handlefenleiInfo(row){
        console.log('分类详情',row)
        // this.$router.push(`/fenleiInfo/type/data/${row.typeId}/${row.typeDetailId}`);
        // this.$router.push(`/fenleiInfo/type/data/${row.typeId}`);
        if (!!row.typeDetailId){
          this.$common.setlocalStorage("typeDetailId",row.typeDetailId)
        }else {
          this.$common.setlocalStorage("typeDetailId",'')
        }
        this.$router.push(`/fenleiInfo/type/data/${row.typeId}`);
      },
      //  属性列表
      handleshuxingList(row){
        console.log('属性列表',row)
        this.$router.push(`/shuxingList/type/data/${row.typeId}`);

      },
      handleUpdate(row) {
        this.reset();
        const typeId = row.typeId || this.ids
        getType(typeId).then(response => {
          console.log(response)
          console.log('点击修改返回值',response.data)
          // response.data.typeUrl =    process.env.VUE_APP_BASE_API + response.data.typeUrl
          if (!!response.data.typeUrl){
            var object = {name:'',url: process.env.VUE_APP_BASE_API+response.data.typeUrl}
            console.log(object)
            this.fileList.push(object)

            // var object = {name:'',url: process.env.VUE_APP_BASE_API+response.data.url}
            // console.log(object)
            // this.fileList.push(object)
          }else {
            this.fileList.length=0
          }
          this.form = response.data;
          this.open = true;
          this.title = "修改分类";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.typeId != undefined) {
              console.log("修改提交的表单",this.form)
              updateType(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addType(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const typeIds = row.typeId || this.ids;
        this.$confirm('是否确认删除分类编号为"' + typeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delType(typeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有分类数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportType(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
